package dao.Product;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import model.Product;
import abstractFactory.Factory;

public class ProductDAOJPA implements ProductDAO{
	EntityManager manager;
	EntityManagerFactory fact;
	
	public EntityManager getManager() {
		if(manager == null) {
			manager = Factory.getFactory().createEntityManager();
		}
		return manager;
	}
	
	public boolean create(Product product) {
		try	{
			getManager().getTransaction().begin();		
			getManager().merge(product);
			getManager().getTransaction().commit();
			getManager().close();
			return true;
		}catch (Exception e) {
			return false;
		}
	}
	
	public List<Product> listAll(){
		getManager().getTransaction().begin();
		Query query = (Query) getManager().createQuery("SELECT p FROM Product p where p.active = 1" );
		@SuppressWarnings("unchecked")
		List<Product> produtos =  query.getResultList();
		getManager().close();
		return produtos;
	}
	
	public List<Product> retrieve(int inicio, int quant, int catId){
		getManager().getTransaction().begin();
		Query query = (Query) getManager().createQuery("SELECT p FROM Product p join p.categories cat where cat.id = :category");
		query.setParameter("category", catId);
		@SuppressWarnings("unchecked")
		List<Product> produtos =  query.setMaxResults(quant).setFirstResult(inicio).getResultList();
		getManager().close();
		return produtos;
	}
	
	public Long totalProduct(){
		getManager().getTransaction().begin();
		Query query = (Query) getManager().createQuery("SELECT count(p) FROM Product p where p.active = 1" );
		Long total = (Long) query.getSingleResult();
		getManager().close();
		return total;
	}
	
	public Long totalProduct(int catId){
		getManager().getTransaction().begin();
		Query query = (Query) getManager().createQuery("SELECT count(p) FROM Product p join p.categories cat where cat.id = :category and p.active = 1" );
		query.setParameter("category", catId);
		Long total = (Long) query.getSingleResult();
		getManager().close();
		return total;
	}
	
	public boolean update(Product product){
		try{
			getManager().getTransaction().begin();
			getManager().merge(product);
			getManager().getTransaction().commit();
			getManager().close();
			return true;
		}catch (Exception e) {
			return false;
		}
	}
	
	public boolean delete(Product product){
		try {
			getManager().getTransaction().begin();
			getManager().merge(product);
			getManager().getTransaction().commit();
			getManager().close();				
			return true;
		} catch (Exception e) {
			return false;
		}
	}
			
	public Product list(int id)	{
		try {
			getManager().getTransaction().begin();	
			Product product = getManager().find(Product.class, id);
			getManager().close();
			return product;
		} catch (Exception e) {
			return null;				
		}
	}
}
